package PersonStu.sanqi;

/**
 * @Author: Dijah
 * @Date: 2022/12/13 13:53
 * @Desc: 给定一个字符串，判断这个字符串最少需要在字符串的尾部插入多少个字符串才能将这个字符变为回文字符串
 */
public class code_15_PMinParts {
    public static int minParts(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        if (s.length() == 1) {
            return 1;
        }
        char[] str = s.toCharArray();
        int N = str.length;
        boolean[][] isP = new boolean[N][N];
        for (int i = 0; i < N; i++) {
            isP[i][i] = true;
        }
        for (int i = 0; i < N - 1; i++) {
            isP[i][i + 1] = str[i] == str[i + 1];
        }
        for (int row = N - 3; row >= 0; row--) {
            for (int col = row + 2; col < N; col++) {
                isP[row][col] = str[row] == str[col] && isP[row + 1][col - 1];
            }
        }
        int[] dp = new int[N + 1];
        for (int i = 0; i <= N; i++) {
            dp[i] = Integer.MAX_VALUE;
        }
        dp[N] = 0;
        for (int i = N - 1; i >= 0; i--) {
            for (int end = i; end < N; end++) {
                // i..end
                if (isP[i][end]) {
                    dp[i] = Math.min(dp[i], 1 + dp[end + 1]);
                }
            }
        }
        return dp[0];
    }


    // 最长回文字符串
    public static String longestPalindrome(String s) {
        // n表示字符串的长度
        int n = s.length();
        String res = null;
        // 定义一个dp数组
        boolean[][] dp = new boolean[n][n];
        // 外层循环控制从最后一个字符向第一个字符渐进
        for (int i = n - 1; i >= 0; i--) {
            // 内层循环控制
            for (int j = i; j < n; j++) {
                // dp数组元素
                dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);

                if (dp[i][j] && (res == null || j - i + 1 > res.length())) {
                    res = s.substring(i, j + 1);
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        String test = "cdeaa";
        String s = longestPalindrome(test);
        System.out.println(s.length());
        System.out.println(minParts(test));
    }
}
